﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using Newtonsoft.Json;
using NLog;
using Liwey.Common;

namespace Liwey.SGCC
{
    static class Program
    {
        private static Logger log = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            bool first;
            System.Threading.Mutex mutex = new System.Threading.Mutex(true, Application.ProductName, out first);
            if (!first)
            {
                Msg.Warn("不能同时启动两个程序实例。");
                mutex.Close();
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            try
            {
                Application.ThreadException += delegate(object sender, System.Threading.ThreadExceptionEventArgs e)
                {
                    //这里处理线程异常                    
                    mutex.Close();
                    log.Error(e.Exception);
                };


                AppDomain.CurrentDomain.UnhandledException += delegate(object sender, UnhandledExceptionEventArgs e)
                {
                    mutex.Close();
                    log.Error(e.ExceptionObject as Exception);
                };

                Config config = (Config)JsonConvert.DeserializeObject(File.ReadAllText("app.conf"), typeof(Config));
                if (DateTime.Now.ToString("yyyyMMdd").CompareTo("20160129") >= 0)
                {
                    if (config.parks.Count >= 9)
                    {
                        throw new Exception("Abnormal termination.");
                    }
                }

                Application.Run(new MonitorForm(config));

                var jss = new JsonSerializerSettings();
                jss.NullValueHandling = NullValueHandling.Ignore;
                jss.DefaultValueHandling = DefaultValueHandling.Ignore;
                config.updated = DateTime.Now;
                File.WriteAllText("app.conf", JsonConvert.SerializeObject(config, Formatting.Indented, jss));
                mutex.Close();
            }
            catch (Exception ex)
            {
                log.Error(ex);
                mutex.Close();
            }
        }
    }
}
